import React, { useEffect, useMemo, useRef, useState } from 'react';
import Tabs from './Tabs';
import { Modal, Switch, Form, Divider, RadioChangeEvent } from 'antd';
import SelectContent from './SelectContent';
import { useBusiness } from '../Context/BusinessContext';
import { IBusinessName } from '../Context/BusinessContext';
import useSyncState from '../hooks/useSyncState';
import SendCardCollection from './SendCardCollection';
import styled from '@emotion/styled';
import AgentService from '@/modules/Agent';
import type { CheckboxValueType } from 'antd/es/checkbox/Group';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import { useTranslation } from 'react-i18next';
import { useCardCollect, IdCardVariableList, BankCardVariableList } from '../Context/CardCollectContext';
import CardVariable from './CardVariable';

interface SendCommandProps {
	visible?: boolean;
	sendCommandModalType?: IBusinessName | null;
	showCustomerRoleOrName?: boolean;
	onOk?: () => void;
	onClose?: () => void;
}

interface customerNameProps {
	name: string | null;
	active: boolean;
	clientId: string;
	id: string;
}

interface customerRoleProps {
	name: string | null;
	active: boolean;
}
const hasDivider = [
	IBusinessName.FILL_FORM,
	IBusinessName.SEND_LINK,
	IBusinessName.SEND_CARD_COLLECTION,
	IBusinessName.SEND_VIDEO_LINK,
	IBusinessName.SEND_PDF,
	IBusinessName.SEND_VARIABLE_COLLECTION,
	IBusinessName.TRANSCRIPT_OF_TESTIMONY,
	IBusinessName.SHARED_PDF,
	IBusinessName.SEND_VIDEO_COLLECTION,
	IBusinessName.SEND_KNOWLEDGE_BASE,
];

const index = (props: SendCommandProps) => {
	const { t } = useTranslation();
	const { visible = false, sendCommandModalType, onOk, onClose, showCustomerRoleOrName } = props;

	const [tabTypes, setTabTypes] = useState<string>('customerNameTabs');

	const [title, setTitle] = useState<string>('');

	const { sendBusiness } = useBusiness();

	const [customerName, setCustomerName] = useState<customerNameProps[]>([]);

	const [customerRole, setCustomerRole] = useState<customerRoleProps[]>([]);

	const [errorMessage, setErrorMessage] = useState<string>('');

	const [selectErrorMessage, setSelectErrorMessage] = useState<string>('');

	const [selectErrorMessageRole, setSelectErrorMessageRole] = useState<string>('');

	const [cardType, setCardType] = useState<string>('idCard'); // 卡证类型

	const [modalWidth, setModalWidth] = useSyncState<number>(520);

	// const [isOcr, setOcrStatus] = useState<boolean>(false);

	const { getVariableValue, enableAutoOcr, autoOcr, setIdCardFront, setIdCardBack, setBankCard } = useCardCollect();

	useEffect(() => {
		if (visible) {
			getTitle();
			getCustomerData();
			getVariableValue();
			// 初始化数据
			setIdCardFront([...IdCardVariableList.front]);
			setIdCardBack([...IdCardVariableList.back]);
			setBankCard([...BankCardVariableList]);
			enableAutoOcr(false);
		} else {
			setCardType(''); // 重置卡证选择状态
			setTabTypes('customerNameTabs');
		}
	}, [visible]);

	const getTitle = async () => {
		switch (sendCommandModalType) {
			case IBusinessName.SEND_CARD_COLLECTION:
				setTitle(t('kazhengshouji') as string);
				break;
			default:
				break;
		}
	};

	const getOkText = (): string => {
		let text = '';
		switch (sendCommandModalType) {
			case IBusinessName.SEND_CARD_COLLECTION:
				text = t('confirm-collect');
				break;
			default:
				text = t('confirm');
				break;
		}
		return text;
	};

	const getCustomerData = () => {
		let customerMembers = AgentService.getCustomerMediaStream();
		let getCustomerName: customerNameProps[] = [];
		let getCustomerRole: customerRoleProps[] = [];
		getCustomerName = customerMembers.map(item => {
			return {
				name: item.userName,
				active: false,
				clientId: item.clientId,
				id: item.id!.toString()
			};
		});
		getCustomerRole = customerMembers.map(item => {
			return {
				name: item.customerRole || '',
				active: false
			};
		});
		getCustomerRole = getCustomerRole.reduce((all: any[], next: { [x: string]: any }) => (all.some((item: { [x: string]: any }) => item['name'] == next['name']) ? all : [...all, next]), []);
		setCustomerName(getCustomerName);
		setCustomerRole(getCustomerRole);
	};

	const selectNameOrRole = (data: any) => {
		let newCustomerName: any = [];
		if (data.clientId) {
			newCustomerName = customerName.map(item => {
				return {
					name: item.name,
					active: item.name === data.name ? true : false,
					clientId: item.clientId
				};
			});
			setCustomerName(newCustomerName);
		} else {
			newCustomerName = customerRole.map(item => {
				return {
					name: item.name,
					active: item.name === data.name ? true : false,
				};
			});
			setCustomerRole(newCustomerName);
		}
	};

	const onChangeCardType = (type: string) => {
		if (type) {
			setCardType(type);
		}
	};

	const getSendData = () => {
		let data: string[] = [];
		let customerMembers = AgentService.getCustomerMediaStream();
		if (showCustomerRoleOrName) {
			if (tabTypes === 'customerNameTabs') {
				customerName.forEach(item => {
					if (item.active) {
						data.push(item.clientId);
					}
				});
			} else {
				customerRole.forEach(item => {
					if (item.active) {
						customerMembers.forEach(ele => {
							if (ele.customerRole === item.name) {
								data.push(ele.clientId);
							}
						});
					}
				});
			}
		} else {
			data.push(customerMembers[0].clientId);
		}

		return data;
	};

	const verification = () => {
		let data = getSendData();
		let flag = false;
		if (data.length === 0) {
			if (tabTypes === 'customerNameTabs') {
				setSelectErrorMessage(sendCommandModalType === IBusinessName.SEND_VARIABLE_COLLECTION ? '*' + t('select-client-for-push') : '*' + t('select-client-role-for-push'));
			} else {
				setSelectErrorMessageRole('*' + t('select-client-role-for-push'));
			}
			flag = true;
		} else {
			setSelectErrorMessage('');
			setSelectErrorMessageRole('');
		}
		if (sendCommandModalType === IBusinessName.SEND_CARD_COLLECTION) {
			if (!cardType) {
				setErrorMessage('*' + t('select-collection-card'));
				flag = true;
			}
		}
		return flag;
	};

	const getSendBusinessType = async () => {
		let data = getSendData();
		switch (sendCommandModalType) {
			case IBusinessName.SEND_CARD_COLLECTION:
				// cmd, data, receivers
				await sendBusiness(cardType === 'idCard' ? IBusinessName.SEND_IDCARD_COLLECTION! : IBusinessName.SEND_BANKCARD_COLLECTION!, {autoOcr: autoOcr()}, data);
				break;
			default:
				break;
		}
	};

	const submit = () => {
		if (verification()) return;
		getSendBusinessType();
		setSelectErrorMessage('');
		setSelectErrorMessageRole('');
		setErrorMessage('');

		onOk && onOk();
	};

	const TitleContianer = styled.p`
		font-size: 13px;
		font-weight: 400;
		color: #202020;
		margin: 0;
	`;

	const handleSwitch = (checked: boolean) => {
		// setOcrStatus(checked);
		enableAutoOcr(checked);
	};

	return (
		<div>
			<Modal
				width={modalWidth()}
				title={title}
				open={visible}
				destroyOnClose={true}
				className="send-command-modal"
				onCancel={() => {
					onClose && onClose();
					setErrorMessage('');
					setSelectErrorMessage('');
					setSelectErrorMessageRole('');
				}}
				onOk={submit}
				okText={getOkText()}
				cancelText={t('cancel')}
			>
				{sendCommandModalType === IBusinessName.SEND_CARD_COLLECTION ? <SendCardCollection onChangeCardType={onChangeCardType} errorMessage={errorMessage} cardType={cardType} /> : ''}

				{showCustomerRoleOrName ? (
					<>
						{sendCommandModalType && hasDivider.indexOf(sendCommandModalType) !== -1 ? <Divider></Divider> : null}
						{sendCommandModalType && hasDivider.indexOf(sendCommandModalType) !== -1 ? <TitleContianer>{t('select-client-for-push')}</TitleContianer> : null}
						{sendCommandModalType === IBusinessName.SEND_VARIABLE_COLLECTION ? null : (
							<Tabs
								tabsType={tabTypes}
								onClick={type => {
									type && setTabTypes(type);
								}}
							/>
						)}
						<SelectContent
							tabTypes={tabTypes}
							array={tabTypes === 'customerNameTabs' ? customerName : customerRole}
							onClick={selectNameOrRole}
							selectErrorMessage={selectErrorMessage}
							selectErrorMessageRole={selectErrorMessageRole}
						/>
					</>
				) : (
					''
				)}
				{cardType && (
					<>
						{' '}
						<Divider></Divider>
						<Form.Item label="OCR识别">
							<Switch checked={autoOcr()} onChange={handleSwitch} />
						</Form.Item>
					</>
				)}
				{autoOcr() && cardType && <CardVariable cardType={cardType} />}
			</Modal>
		</div>
	);
};

export default index;
